<template>
  <div id="app">
    <!-- 主界面 -->
    <v-app v-if="!islocked">
      <v-toolbar dense flat fixed app background="primary">
        <v-layout>
          <v-menu offset-y>
            <v-btn slot="activator" flat>开始</v-btn>
            <v-list>
              <v-list-tile
                v-for="(item, index) in ['管理员', '服务端口', '注销','退出']"
                :key="index"
                @click="menuStartClick(item)"
              >
                <v-divider v-if="item == '退出'" dark></v-divider>
                <v-list-tile-title>{{item}}</v-list-tile-title>
              </v-list-tile>
            </v-list>
          </v-menu>
          <v-spacer></v-spacer>
          <v-menu offset-y>
            <v-btn slot="activator" flat>车位监控</v-btn>
            <v-list>
              <v-list-tile
                v-for="(item, index) in ['所有摄像头', '车位状态']"
                :key="index"
                @click="parkingDetect(item)"
              >
                <v-list-tile-title>{{item}}</v-list-tile-title>
              </v-list-tile>
            </v-list>
          </v-menu>
          <v-spacer></v-spacer>
          <v-menu offset-y>
            <v-btn slot="activator" flat>收费</v-btn>
            <v-list>
              <v-list-tile
                v-for="(item, index) in ['计时', '设置收费', '历史收费统计']"
                :key="index"
                @click="chargeCount(item)"
              >
                <v-list-tile-title>{{item}}</v-list-tile-title>
              </v-list-tile>
            </v-list>
          </v-menu>
          <!-- <v-spacer></v-spacer>
          <v-menu offset-y>
            <v-btn slot="activator" flat>初始化车位</v-btn>
            <v-list>
              <v-list-tile @click="loadParkingPosition">
                <v-list-tile-title>载入车位信息</v-list-tile-title>
              </v-list-tile>
            </v-list>
          </v-menu>-->
          <v-spacer></v-spacer>
          <v-menu offset-y>
            <v-btn slot="activator" flat>摄像头管理</v-btn>
            <v-list>
              <v-list-tile
                v-for="(item, index) in ['摄像头状态', '正常摄像头', '故障摄像头']"
                :key="index"
                @click="cameraManager(item)"
              >
                <v-list-tile-title>{{item}}</v-list-tile-title>
              </v-list-tile>
            </v-list>
          </v-menu>
          <v-spacer></v-spacer>
          <v-menu offset-y>
            <v-btn slot="activator" flat>帮助</v-btn>
            <v-list>
              <v-list-tile v-for="(item, index) in ['使用说明', '关于']" :key="index" @click="help(item)">
                <v-list-tile-title>{{item}}</v-list-tile-title>
              </v-list-tile>
            </v-list>
          </v-menu>
        </v-layout>
      </v-toolbar>
      <v-content>
        <keep-alive>
          <router-view></router-view>
        </keep-alive>
      </v-content>
    </v-app>

    <!-- 登陆注册 -->
    <v-app v-else>
      <v-content>
        <v-container>
          <v-card flat height="500">
            <v-card-title>登陆/注册</v-card-title>
            <v-card-text>
              <v-card class="mx-auto" max-width="400">
                <v-card-title class="title font-weight-regular justify-space-between">
                  <span>{{ currentTitle }}</span>
                </v-card-title>

                <v-window v-model="step">
                  <v-window-item :value="1">
                    <v-card-text>
                      <v-form ref="loginForm">
                        <span class="red--text" v-show="isLoginFailed">账号或者密码输入错误！</span>
                        <v-text-field
                          label="账号"
                          v-model="account"
                          :rules="namerules"
                          validate-on-blur
                        ></v-text-field>
                        <v-text-field
                          label="密码"
                          type="password"
                          v-model="password"
                          :rules="passrules"
                          validate-on-blur
                        ></v-text-field>
                      </v-form>
                      <span class="caption grey--text text--darken-1">请输入账号和密码登陆。</span>
                      <!-- <v-layout>
                        <v-text-field
                          label="远程服务端口"
                          type="text"
                          :rules="ipRules"
                          outline
                          single-line
                          v-model="remote_ip"
                          @change="remote_connect_fix"
                          ref="remoteIp"
                        >
                        </v-text-field>
                        <v-btn large @click="connect2remote">连接</v-btn>
                      </v-layout> -->
                      <!-- <span class="red--text" v-show="isDisconnected">连接失败！</span> -->
                    </v-card-text>
                  </v-window-item>

                  <v-window-item :value="2">
                    <v-card-text>
                      <v-form ref="registForm">
                        <v-text-field
                          label="账号"
                          v-model="account"
                          :rules="namerules"
                          validate-on-blur
                        ></v-text-field>
                        <v-text-field
                          label="密码"
                          type="password"
                          v-model="password"
                          :rules="passrules"
                        ></v-text-field>
                      </v-form>
                      <span class="text--darken-1 caption grey--text">请牢记你的账号和密码！</span>
                    </v-card-text>
                  </v-window-item>
                </v-window>
                <v-card-actions>
                  <v-spacer></v-spacer>
                  <v-btn v-show="step == 1" @click="login" color="success">登陆</v-btn>
                  <v-spacer></v-spacer>
                  <v-btn color="primary" depressed @click="regist" v-show="step==2">确认</v-btn>
                </v-card-actions>
              </v-card>
            </v-card-text>
          </v-card>
        </v-container>
      </v-content>
    </v-app>

    <v-dialog v-model="isshowabout" width="500">
      <v-card>
        <v-card-title class="headline grey lighten-2" primary-title>关于本软件</v-card-title>

        <v-card-text>
          <v-layout row wrap>
            <v-flex sm3>
              <v-img></v-img>
            </v-flex>
            <v-divider vertical></v-divider>
            <v-spacer></v-spacer>
            <v-flex sm8>
              <article>智能停车管理系统 0.1.0
                <br>
                <br>Base on Qt5.11.1 (MSVC 2015, 64bit)
                <br>Base on Electron (MSVC 2015, 64bit)
                <br>Built on 2018.12.20 10:33:2
                <br>From reversion 0.0.9
                <br>版权2018-2028 南昌航空大学 ©版权所有
                <br>该项目由南昌航空大学计算机视觉研究所研发
                <br>
                <br>
              </article>
            </v-flex>
          </v-layout>
        </v-card-text>

        <v-divider></v-divider>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="primary" flat @click="isshowabout = false">关闭</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import fs, { truncate } from "fs";
import path from "path";
import { mapState } from "vuex";
import api from "./lib/httpapi.js";
// import {app} from 'electron'
// import {APP_EXIT} from './lib/singal.js'
import socketio from 'socket.io-client'
import { ipcMain } from 'electron';
const shell = require("electron").shell;
const ipCheck = (v)=>(/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/.test(v))

export default {
  name: "Parkings",
  data: any => ({
    isshowabout: false, //是否显示关于信息弹窗
    islocked: true, // 是否验证登陆
    isregist: false, // 是否需要进行首次运行注册
    isLoginFailed: false, // 登陆失败消息显示控制器
    step: 1, // 显示登陆或者注册窗口控制器
    account: "", //账号
    password: "", // 密码
    remote_ip: '',   // 远程ip地址
    isDisconnected: false, // 连接服务器状态控制器
    namerules: [v => !!v || "不能为空！"],
    passrules: [
      v => !!v || "不能为空！",
      v => v.length >= 6 || "密码长度不能少与六个字符"
    ],
    ipRules: [
      v => !!v || "不能为空！",
      v => ipCheck(v) || "非法的IP地址！",
    ]
  }),

  methods: {
    // 连接远程服务器
    connect2remote() {
      if(this.$refs.remoteIp.validate()) { 
        if(!this.remote_ip || !ipCheck(this.remote_ip)) {
          this.isDisconnected = true
          return
        }
        const socket = socketio(this.remote_ip)
        this.$socket = socket
      }
    },

    remote_connect_fix() {
      this.isDisconnected = false
    },
    
    // 首次注册账号
    async regist() {
      const account = (this.account || "").trim();
      const password = (this.password || "").trim();
      if (this.$refs.registForm.validate()) {
        await this.$store.dispatch("startmenu/insert", {
          username: account,
          password: password
        });
        if (this.$store.getters["startmenu/all"].length > 0) {
          this.step = 1;
        }
        this.$refs.registForm.reset();
        this.account = "";
        this.password = "";
      }
    },

    // 登陆
    login() {
      this.isLoginFailed = false;
      const account = (this.account || "").trim();
      const password = (this.password || "").trim();
      if (this.$refs.loginForm.validate()) {
        this.$store.commit("startmenu/verify", {
          username: account,
          password: password
        });
        if (this.$store.state["startmenu"]["isVerify"]) {
          this.$refs.loginForm.reset();
          this.account = "";
          this.password = "";
          this.islocked = false;
          this.isLoginFailed = false;
        } else {
          this.isLoginFailed = true;
        }
      }
    },

    // 开始按钮
    menuStartClick(item) {
      if (item == "管理员") {
        this.$router.push({ path: "/start/admin" });
      } else if (item == "服务端口") {
        this.$router.push("/start/server_port");
      } else if (item == "注销") {
        this.$store.commit("startmenu/logout");
        this.islocked = true;
        if (this.$store.getters["startmenu/all"].length > 0) {
          this.step = 1;
        } else {
          this.step = 2;
        }
      } else {
        const {app} = require('electron')
        app.exit(0)
      }
    },
    // 车位监测
    parkingDetect(item) {
      if (item == "所有摄像头") this.$router.push({ path: "/" });
      else if (item == "车位状态")
        this.$router.push({ path: "/parking_status" });
    },
    // 收费
    chargeCount(item) {
      if (item == "计时") this.$router.push("/charge/timer");
      else if (item == "设置收费") this.$router.push("/charge/setfee");
      else if (item == "历史收费统计") this.$router.push("/charge/history");
    },
    // 载入初始化车位位置信息
    // loadParkingPosition() {
    //   this.$router.push("/inital_parking_part");
    // },
    // 摄像头管理
    cameraManager(item) {
      if (item == "摄像头状态") this.$router.push("/camerastatus/all");
      else if (item == "正常摄像头") this.$router.push("/camerastatus/normal");
      else this.$router.push("/camerastatus/fault");
    },
    // 帮助
    help(item) {
      if (item == "使用说明") {
        fs.exists(__dirname + "./assets/help/使用说明.pdf", exists => {
          if (!exists) {
            this.$router.push("/usage");
          } else {
            shell.showItemInFolder(
              path.join(process.cwd(), __dirname, "assets/help/*/")
            );
          }
        });
        // this.$router.push("/usage")
      } else if (item == "关于") {
        this.isshowabout = true;
      }
    },

    initial() {
      if (this.$store.state.is_init) return;
      // 绑定视频更新
      this.$socket.on("video", data => {
        if (typeof data == "string") data = JSON.parse(data);
        ebus.$emit("video_update", data);
      });

      api.get("/init");
      this.$socket.on("init_parkings", data => {
        if (typeof data == "string") data = JSON.parse(data);
        this.$store.commit("parkingmonitor/initParkingStatus", data.data);
      });

      this.$socket.on("update_parkings", data => {
        if (typeof data == "string") data = JSON.parse(data);
        this.$store.commit("parkingmonitor/updateParkingStatus", data.data);
      });

      this.$socket.on("init_cameras", data => {
        if (typeof data == "string") data = JSON.parse(data);
        this.$store.commit("camerastatus/initCameras", data.data);
        let cameras = [];
        data.data.map(v => (!!v.cam ? cameras.push(v.cam) : null));
        cameras = cameras.filter(v => v !== null);
        this.$store.commit("parkingmonitor/setCamera", cameras);
      });

      this.$socket.on("update_camera", data => {
        if (typeof data == "string") data = JSON.parse(data);
        this.$store.commit("camerastatus/updateCameras", data.data);
      });

      // this.$store.commit("isInited", true);
    }
  },
  async created() {
    this.$store.commit("parkingmonitor/setCamera", ["jk123", "jk124"]);
    await this.$store.dispatch("startmenu/init");
    this.initial();
    if (this.$store.getters["startmenu/all"].length == 0) {
      this.step = 2;
    }
  },
  async mounted() {
    try {
      const res = await api.ping("/ping");
      if (res.status == 200) {
        let data = res.data;
        this.$store.commit("startmenu/ping", data);
      }
    } catch (err) {}
  },

  computed: {
    currentTitle() {
      switch (this.step) {
        case 1:
          return "登陆";
        case 2:
          return "首次登陆注册账号";
      }
    }
  }
};
</script>

<style>
/* CSS */
</style>
